<template>
    <div>
         <!-- 面包屑区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片区域 -->
        <el-card>
            <!-- 头部区域 -->
            <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable ="false"></el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>

                    <!-- 选择商品分类的级联选择器 -->
                    <el-cascader 
                    v-model="selectCateKeys" :options="cateList" :props="cateProps" @change="handleChange">

                    </el-cascader>
                </el-col>
            </el-row>

            <!-- tab 页签 -->
             <el-tabs v-model="activeName" @tab-click="handleTabClick">
                 <!-- 动态参数区域 -->
                <el-tab-pane label="动态参数" name="many">
                    <!-- 动态参数按钮 -->
                    <el-button size="mini" type="primary" :disabled="isDisaboled" @click="addDialogVisible = true">添加参数</el-button>

                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">

                                <!-- 循环tag数据项 -->
                                <el-tag closable :key="i" v-for = "(item,i) in scope.row.attr_vals" @close = "handleClose(i,scope.row)">{{item}}</el-tag>

                            <!-- 添加tag项 button和input -->
                            <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index">
                        </el-table-column>
                        <el-table-column label="参数名称" prop="attr_name">
                        </el-table-column>
                         <el-table-column label="操作" >
                             <template slot-scope = "scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                 <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                             </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!-- 静态参数区域 -->
                <el-tab-pane label="静态参数" name="only">
                    <!-- 静态参数按钮 -->
                    <el-button size="mini" type="primary" :disabled="isDisaboled" @click="addDialogVisible = true">添加属性</el-button>

                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">

                                <!-- 循环tag数据项 -->
                                <el-tag closable :key="i" v-for = "(item,i) in scope.row.attr_vals" @close = "handleClose(i,scope.row)">{{item}}</el-tag>

                            <!-- 添加tag项 button和input -->
                            <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index">
                        </el-table-column>
                        <el-table-column label="属性名称" prop="attr_name">
                        </el-table-column>
                         <el-table-column label="操作" >
                             <template slot-scope = "scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                 <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                             </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数 对话框 -->
        <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
        >

            <!-- form 表单区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑参数 对话框 -->
         <el-dialog
        :title="'修改' + titleText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
        >

            <!-- form 表单区域 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return{
            //商品分类数据列表
            cateList:[],
            //分类规则
            cateProps:{
                expandTrigger :'hover',
                 value:'cat_id' ,
                 label:'cat_name',
                 children:'children',
                 
            },
            //级联选择器双向绑定到的数组
            selectCateKeys:[],
            //被激活的Tab name
            activeName:'many',
            //动态数据列表
            manyTableData:[],
            //静态数据列表
            onlyTableData:[],
            //控制 添加参数 对话框 显示与隐藏
            addDialogVisible:false,
            //所有表单数据
            addForm:{
                attr_name:'',
            },
            //表单属性验证规则
            addFormRules:{
                attr_name:[
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ]
            },
            //控制修改对话框的显示与隐藏
            editDialogVisible:false,
            //修改表单的所有数据
            editForm:{
                
            },
            //修改表单  数据验证规则
            editFormRules:{
                attr_name:[
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ]
            }
        }
    },
    created(){
        this.getCateList()
    },
    methods:{
        //获取商品分类数据列表
        async getCateList(){
            const {data : res} = await this.$http.get('categories')
            if(res.meta.status !== 200){
                return this.$message.error('获取商品分类失败！')
            }
            this.cateList = res.data
            // console.log(this.cateList);
        },
        // 级联选择框选中项变化，会触发这个函数
        handleChange(){
            // console.log(this.selectCateKeys);
            this.getParamsList()
        },
        //点击tab 页签触发的点击事件
        handleTabClick(){
            // console.log(this.activeName);
             this.getParamsList()
            
        },
        //获取参数列表数据
        async getParamsList(){
            //证明选中的不是三级分类
            if(this.selectCateKeys.length !== 3){
               this.selectCateKeys = []
               this.manyTableData = []
               this.onlyTableData = []
               return
            }
             const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                params:{sel:this.activeName}
            })
            if(res.meta.status !== 200){
                return this.message.error('获取参数失败！')
            }
            //循环data 数组拿到 json对象 然后拿到对象下的字符串 再转化成数组 为后续渲染页面 for循环使用
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals == '' ? [] : item.attr_vals.split(' ')

                    //给每一项添加自己的 inputVisible和inputValue
                    item.inputVisible = false
                    item.inputValue = ''
                })
            // console.log(this.ParamsList);
            
            // console.log(res.data);
            if(this.activeName == "many"){
                this.manyTableData = res.data       
            }else{
                this.onlyTableData =res.data 
            }
        },
        //关闭时清空验证 和数据
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        //添加参数或属性事件
        addParams(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return
               const {data:res} =  await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName,
                })
                // console.log(res);
                
                if(res.meta.status !== 201) return
                this.$message.error('获取参数失败！')
                this.$message.success('获取参数成功！')
                this.addDialogVisible = false
                this.getParamsList()
            })
        },
        //点击编辑按钮展示对话框
        async showEditDialog(attr_id){
          
            //查询当前参数信息
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{
               params:{
                    attr_sel:this.activeName,
               }
            })
            if(res.meta.status !==200) return this.$message.error('获取参数失败！')
            this.editForm = res.data
            this.editDialogVisible = true
        },
        //关闭修改对话框 清除数据和验证
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        //点击修改对话框   确定按钮事件
        editParams(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return;
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                    attr_name:this.editForm.attr_name,
                    attr_sel:this.activeName 
                })
                if(res.meta.status !== 200) return this.$message.error('修改参数失败！');
                this.$message.success('修改参数成功！')
                this.getParamsList()
                this.editDialogVisible = false
            })
        },
        //点击修改对话框   删除按钮监听
        removeParams(id){
             this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async () => {
                    const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
                    if(res.meta.status !== 200) return this.$message.error('获取参数失败！')
                    this.$message.success('删除成功！')
                    this.getParamsList()
                    this.editDialogVisible =false
                }).catch(() => {
                    this.$message.info('取消删除！')
                })     
            
        },
        //按下enter 或 失去焦点后触发的事件
        handleInputConfirm(row){
            //验证文本框中是否为空格或者为空
            if(row.inputValue.trim().length === 0){
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            //不为空时  继续执行下列代码
            //给需要循环的数据添加新增项
            row.attr_vals.push(row.inputValue.trim())

            //调用接口更新后台数据
            this.saveAttrVals(row)
            row.inputValue = ''
            row.inputVisible = false
        },
        //参数项后台数据接口调用
        async saveAttrVals(row){
             const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:this.activeName,
                //后台以字符串空额的形式存储，需要把数组转换成字符串
                attr_vals:row.attr_vals.join(' ')
            })
            if(res.meta.status !== 200) return this.$message.error('请求参数项失败！');
            this.$message.success('请求参数项成功！')
            // console.log(res);  
        },
        //点击button按钮后   显示input 
        showInput(row){
            row.inputVisible = true
            //该对象 等到 页面再次被渲染后执行  为了能更好的获取Input Dom对象
            this.$nextTick(_ => {
            //获取DOM对象  然后调用获取焦点方法
            this.$refs.saveTagInput.$refs.input.focus();
        });
        },
         //删除对应的tag项
        handleClose(i,row){
            row.attr_vals.splice(i,1)
            this.saveAttrVals(row)
        }
    },
    computed:{
        //button 禁止和开启
        isDisaboled(){
            if(this.selectCateKeys.length !== 3){
                return true
            }else{
                 return false
            }
        },
        //获取分类请求id,也就是数组的最后一项,否者返回空 发起数据请求所需
        cateId(){
            if(this.selectCateKeys.length == 3){
                return this.selectCateKeys[2]
            }else{
                return null
            }
        },
        //添加参数 对话框 title切换
        titleText(){
            if(this.activeName == 'many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    }
}
</script>
<style lang="less" scoped>
    .cat_opt{
        margin:15px 0;
    }
    .el-tag{
        margin-right:15px;
    }
   .input-new-tag{
       width: 120px;
   }
</style>